package br.usp.ime.origami.primitives;

import br.usp.ime.origami.model.Point;
import br.usp.ime.origami.model.SimplePoint;

public class AnglePrimitives
{

	public static double bissectorDirection(Point before, Point middle, Point after) {
		double x1 = middle.getX() - before.getX();
		double y1 = middle.getY() - before.getY();
		double x2 = after.getX() - middle.getX();
		double y2 = after.getY() - middle.getY();
	
		double p1Size = Math.sqrt(x1 * x1 + y1 * y1);
		double p2Size = Math.sqrt(x2 * x2 + y2 * y2);
	
		x1 /= p1Size;
		y1 /= p1Size;
		x2 /= p2Size;
		y2 /= p2Size;
	
		return angleBetween(new SimplePoint(1, 0), new SimplePoint(0, 0), new SimplePoint(x2 - x1, y2 - y1));
	}

	public static double angleBetween(Point before, Point middle, Point after) {
	
		double x1 = middle.getX() - before.getX();
		double y1 = middle.getY() - before.getY();
		double x2 = after.getX() - middle.getX();
		double y2 = after.getY() - middle.getY();
	
		double dotProduct = x1 * x2 + y1 * y2;
	
		double p1Size = Math.sqrt(x1 * x1 + y1 * y1);
		double p2Size = Math.sqrt(x2 * x2 + y2 * y2);
		double cos = dotProduct / (p1Size * p2Size);

		// TODO teve um caso que cos = -1.0000000000000002
		// e ai Math.acos(cos) devolve NaN
		// vou tentar resolver com o if abaixo
		double angle;
		if(cos < -1)
			angle = Math.PI;
		else if(cos > 1)
			angle = 0;
		else
			angle = Math.acos(cos);

		if (BasicPrimitives.left(before, middle, after)) {
			angle = Math.PI + angle;
		} else {
			angle = Math.PI - angle;
		}
	
		
		return angle;
	}

	public static double baseAngle(Point p1, Point p2) {
		return angleBetween(new SimplePoint(p1.getX() + 1, p1.getY()), p1, p2);
	}

}
